function copyResult(val){
	var oInput = document.createElement('textarea');
	oInput.value = val;
	document.body.appendChild(oInput);
	oInput.select(); // 选择对象
	document.execCommand("Copy"); // 执行浏览器复制命令
    document.body.removeChild(oInput);
}
function getEleByID(id) {
	return document.getElementById(id);
}

function countWordNum() {
	var text = getEleByID("match-content").value;
	getEleByID("match-word-num").innerText = text.length;
	getEleByID("en-char-num").innerText = FormatUtil.getEnChCount(text);
}

function storageText() {
	var text = getEleByID("match-content").value;
	if(window.localStorage)window.localStorage.setItem("matchText", text);
}


function replaceChineseNum(e) {
	var inputTextarea = getEleByID("match-content");
	var reg = new RegExp(e.getAttribute('data-num'), 'g');
	var text = inputTextarea.value;
	inputTextarea.value = text.replace(reg, e.innerText);
}

function replaceEnPunctuation(){
	var inputTextarea = getEleByID("match-content");
	var text = inputTextarea.value;
	var obj = {
		",": "，",
		"!": "！",
		"\\?": "？",
		";": "；",
		":": "：",
		"\\(": "（",
		"\\)": "）",
		"--": "——",
	};
	for (var key in obj) {
		text = text.replace(new RegExp(key, "g"), obj[key]);
	}
	inputTextarea.value = text;
}
function fillZero(num) {
	return (num < 10 ? '0' : '') + num;
}

function getFmtDateStr(date) {
	return date.getFullYear() + '-' +
		fillZero(date.getMonth() + 1) + '-' +
		fillZero(date.getDate());
}

function getFmtDateWeekStr(str) {
	var date = new Date(str.substr(0, 4), str.substr(5, 2) - 1, str.substr(8, 2) - 0);
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var day = date.getDate();
	var week = date.getDay();
	var weekStr = "星期" + "日一二三四五六".charAt(week);
	var res = year + '年' +
		fillZero(month) + '月' +
		fillZero(day) + "日" +
		weekStr
	return res;
}

function getDLDateByPeriod(stage) {
	var date = new Date(2015, 3 - 1, 31 + stage);
	return getFmtDateStr(date);
}

function downloadTextFile(fileName, content) {
	var data = new Blob([content]);
	var downloadUrl = window.URL.createObjectURL(data);
	var anchor = document.createElement("a");
	anchor.href = downloadUrl;
	anchor.download = fileName;
	anchor.click();
	window.URL.revokeObjectURL(data);
}
function addWordCount(n){
	var v = document.getElementById("cut-select").value;
	v = parseInt(v);
	v = Math.min(Math.max(150, v + n), 600);
	document.getElementById("cut-select").value = v;
	document.getElementById("cut-num-sp").innerText = v + "字";

	console.log(v);
}
window.onload = function () {
	var inputTextarea = getEleByID("match-content");

	var statusSpan = getEleByID("status-text");
	var formatBtn = getEleByID("format-btn");
	var copyBtn = getEleByID("copy-text-btn");
	var resetBtn = getEleByID("reset-btn");
	var cutBtn = getEleByID("cut-btn");
	var cutSel = getEleByID("cut-select");
	var repBtn = getEleByID("replace-btn");

	var orgIpt = getEleByID("original-ipt");
	var repIpt = getEleByID("rep-ipt");



	var autoRepDiv = getEleByID("auto-rep-div");
	var cutTitleIpt = getEleByID("cut-title-ipt");

	var uploadFmtBtn = getEleByID("upload-fmt-btn");
	var beginUpStage = getEleByID("begin-up-stage");


	if(window.localStorage)inputTextarea.value = window.localStorage.getItem("matchText") || "";
	countWordNum();

	resetBtn.onclick = function () {
		if(window.localStorage)window.localStorage.removeItem("matchText");
		location.reload();
	}

	formatBtn.onclick = function () {
		var text = inputTextarea.value;
		var fmtStr = FormatUtil.getFormatStr(text);
		inputTextarea.value = fmtStr;
		statusSpan.innerHTML = FormatUtil.getStatusHTML(fmtStr);
		countWordNum();
		getEleByID("gbk-num").innerText = FormatUtil.getOUT3500(fmtStr);
	}
	
	cutBtn.onclick = function () {
		var cutTitle = cutTitleIpt.value.trim();
		var addCutTitle = function (cutContent, cutTitle) {
			var res = '';
			var contentArr = cutContent.match(new RegExp('.+', 'g')) || [];
			var len = contentArr.length;
			for (var i = 0; i < len; i++) {
				res += cutTitle + "（" + (i + 1) + "/" + len + "）\r\n";
				res += contentArr[i] + "\r\n\r\n\r\n";
			}
			return res;
		}
	
		var cutNum = cutSel.value - 0;
		var text = inputTextarea.value;
		if (cutTitle) {
			text = text.replace(new RegExp(cutTitle + '（\\d{1,3}/\\d{1,3}）', 'g'), '');
		}
		var fmtStr = FormatUtil.getFormatStr(text);
		var cutContent = FormatUtil.getCutStr(fmtStr, cutNum);
		if (cutTitle) {
			cutContent = addCutTitle(cutContent, cutTitle);
		}
		
		inputTextarea.value = cutContent;
		statusSpan.innerHTML = FormatUtil.getStatusHTML(fmtStr);
		countWordNum();
		getEleByID("gbk-num").innerText = FormatUtil.getOUT3500(fmtStr);
		layer.closeAll();
	}

	repBtn.onclick = function () {
		if (!orgIpt.value) {
			return;
		}
		var reg = new RegExp(orgIpt.value, 'g');
		var text = inputTextarea.value;
		inputTextarea.value = text.replace(reg, repIpt.value);
		orgIpt.value = '';
		repIpt.value = '';
		layer.closeAll();
	}
	



	var alinks = autoRepDiv.children;
	for (var i = 0; i < alinks.length; i++) {
		(function (i) {
			var alink = alinks[i];
			alink.onclick = function () {
				orgIpt.value = this.getAttribute("data-rep");
				repIpt.value = this.getAttribute("to-rep") || "";
			}
		})(i);
	}

	uploadFmtBtn.onclick = function () {
		var period = Number(beginUpStage.value || 1);
		var text = inputTextarea.value;
		var arr = text.match(/.+/g) || [];
		arr = arr.map(function(item){return item.trim()});
		arr = arr.filter(function(item){return !!item});
		if (arr.length % 2 != 0) {
			layer.msg("格式错误，标题和内容数量不一致", {icon: 2});
			return;
		}
		var str = "";
		var matchList = new Array();
		var uploadName = document.querySelector("#match-upload-name").value.trim();
		for (var i = 0; i < arr.length; i += 2) {
			str += arr[i] + (uploadName ? "-" + uploadName + "上传-" : "") + "\r\n";
			str += (arr[i + 1] || "") + "\r\n";
			str += "\r\n";

			var obj = new Object();
			obj.period = period + parseInt(i / 2);
			obj.date = getDLDateByPeriod(obj.period);
			obj.title = arr[i];
			obj.content = arr[i + 1];
			matchList.push(obj);
		}
		inputTextarea.value = str;

		// var backUpStr = "";
		// for(var k in matchList) {
		// 	var obj = matchList[k];
		// 	backUpStr += getFmtDateWeekStr(obj.date) + '\n';
		// 	backUpStr += obj.title + (obj.period ? '第' + obj.period + '期' : '') + '-zhiyihu上传\n';
		// 	backUpStr += obj.content + '\n';
		// 	backUpStr += '-----第' + 999 + '段-' + obj.content.length + 'Z-type--xc.sw.2.0\n\n\n';
		// }
	}

	copyBtn.onclick = function(){
		var text = getEleByID("match-content").value;
		if(!text){
			layer.msg("文本为空，未复制");
			return;
		}
		copyResult(text);
		layer.msg("复制文本成功", {icon: 1});
	}

	document.querySelector("#mobile-upload-fmt-btn").onclick = function(){
		document.querySelector("#upload-fmt-btn").click();
	}

	document.querySelector("#mobile-cut-btn").onclick = function(){
		var content = $("#cut-text-part");
			layer.open({
			type: 1,
			content: content,
			shadeClose: true,
			title: " ",
			area: ["340px", "auto"],
		});
	}

	document.querySelector("#mobile-replace-btn").onclick = function(){
		var content = $("#replace-text-part");
			layer.open({
			type: 1,
			content: content,
			shadeClose: true,
			title: " ",
			area: ["340px", "auto"],
		});
	}

	var c = function(){
		var key = this.getAttribute("key");
		var content = editCustomPart.innerHTML;
		var lengthKeys = ["L1sw"];
		var muchSensorIdKeys = ["L3hs"];
		var isMobile = screen.width < 500;
		var h = !lengthKeys.includes(key)&&!muchSensorIdKeys.includes(key) ? 280 : 320;
		var w = isMobile ? 320 : 420;
		h += isMobile ? 40 : 0;
		layer.open({
			type: 1,
			content: content,
			shadeClose: true,
			title: " ",
			area: [w + 'px', h + 'px'],
		});
		var okBtn = document.querySelector(".layui-layer-content #okBtn");
		var addCustomSensorBtn = document.querySelector(".layui-layer-content #addCustomSensorBtn");
		var addCustomSensorDiv = document.querySelector(".layui-layer-content #addCustomSensorDiv");
		var addCustomNumLenDiv = document.querySelector(".layui-layer-content #addCustomNumLenDiv");
		var customSensorIdIpt = document.querySelector(".layui-layer-content input[name='customSensorId']");
		var customSensorNumberIpt = document.querySelector(".layui-layer-content input[name='customSensorNumber']");
		var customSensorLengthIpt = document.querySelector(".layui-layer-content input[name='customSensorLength']");
		var layerPageDiv = document.querySelector(".layui-layer-page");
		var layerContentDiv = document.querySelector(".layui-layer-content");
		var sensorIdDiv = document.querySelector(".layui-layer-content #sensorIdDiv");
		var sensorNumDiv = document.querySelector(".layui-layer-content #sensorNumDiv");
		var addCustomNumLenBtn = document.querySelector(".layui-layer-content #addCustomNumLenBtn");
		if(muchSensorIdKeys.includes(key)){
			addCustomSensorBtn.style.display = "";
		}
		if(lengthKeys.includes(key)){
			addCustomNumLenBtn.style.display = "";
			customSensorLengthIpt.parentNode.style.display = "";
			customSensorNumberIpt.style.width = !isMobile ? "84px" : "125px";
			sensorNumDiv.children[0].innerText = com.text(".sensor-number-length");
		}
		addCustomSensorBtn.onclick = function(e){
			var div = document.createElement("div");
			var label = sensorIdDiv.children[0].cloneNode(true);
			var text = label.innerText;
			var lastCh = text.charAt(text.length - 1);
			var order = (addCustomSensorDiv.children.length + 2);
			text = text.substr(0, text.length-1) + " "+ order + lastCh;
			label.innerText = text;
			var input = sensorIdDiv.children[1].cloneNode(false);
			var sensorIdVal = (sensorIdDiv.children[1].value || "").trim();

			if(sensorIdVal.charAt(sensorIdVal.length - 1)=="1"){
				input.value = sensorIdVal.substr(0, sensorIdVal.length - 1) + order;
			}else if(sensorIdVal){
				input.value = sensorIdVal + order;
			}else{
				input.value = "";
			}
			div.appendChild(label);
			div.appendChild(input);
			addCustomSensorDiv.appendChild(div);
			var h = Math.min((!isMobile ? 500 : 360), layerPageDiv.offsetHeight + (!isMobile ? 49 : 70));
			layerPageDiv.style.height = h + "px";
			layerContentDiv.style.height = h - 51 + "px";
		}
	}
}

document.onkeydown = function (e) {
	if (e.ctrlKey && e.keyCode == 83) {
		e.returnValue = false;
		return;
	}
}